<template>
  <div>
    <!-- 图表 -->
    <div class="chart">
      <div class="chart-header task-flex task-ai">
        <div class="task-span1">
          <div class="chart-icon" :class="styles(chartType)"><i class="iconfont" :class="chartType"></i></div>
        </div>
        <div class="task-flex task-pointer">
          <div @click="exportBtn" class="task-export-text" v-show="type === $t('common.base.table2') && auth.REPORT_EXPORT">
            <i class="iconfont icon-upload1"></i>
            {{ $t('common.base.export') }}
          </div>
          <div @click="$emit('checkDate')" id="custom-report-data">
            <i class="iconfont icon-filter"></i>
            {{$t('report.customReportAggregate.title5')}}
            <i class="iconfont icon-triangle-down"></i>
          </div>
          <div class="task-ml12 task-pointer">
            <el-dropdown @command="handleClick">
              <div>
                <i class="iconfont icon-paixu1"></i>
                {{sort}}
                <i class="iconfont icon-triangle-down"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="$t('report.productChart.defaultSort')">{{$t('report.productChart.defaultSort')}}</el-dropdown-item>
                <el-dropdown-item :command="$t('report.productChart.priceSort1')">{{$t('report.productChart.priceSort1')}}</el-dropdown-item>
                <el-dropdown-item :command="$t('report.productChart.priceSort2')">{{$t('report.productChart.priceSort2')}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="task-ml12" @click="convertCanvasToImage" v-show="type !== $t('common.base.table2')">
            <i class="iconfont icon-cloud-download"></i>
            {{ $t('product.component.qrcodeDialog.btn2') }}
          </div>
        </div>
      </div>
      <no-data-view-new v-if="!chartList.length && !loading" :notice-msg="`${tableTitle && type ? $t('common.base.tip.noData') : $t('report.customReportAggregate.pla1')}`"></no-data-view-new>
      <!-- 图表 -->
      <div class="chart-content" id="custom-report-chart" v-if="type !== $t('common.base.table2') && chartList.length">
        <div id="chart"></div>
      </div>
      <!-- table -->
      <div id="chart-table-position" :class="{'chart-table': chartList.length > 15}" v-if="type === $t('common.base.table2') && chartList.length">
          <el-table
          id="table-wrap"
          stripe
          border
          :data="chartList"
          ref="multipleTable"
          @row-click="tabletd"
          :row-class-name="rowClassName"
          header-row-class-name="common-list-table-header taks-list-table-header"
        >
          <el-table-column :label="tableTitle">
            <template slot-scope="scope">
              <div class="task-pointer">
                <template v-if="isOpenData && scope.row.staffId">
                  <open-data type='userName' :openid="scope.row.staffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row.name}}
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('report.customReportAggregate.total')">
            <template slot-scope="scope"><div class="task-pointer">{{scope.row.count}}</div></template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table task-mt12" v-show="tableNames.length">
      <div class="export-table-style">
      <div class="chart-header task-flex task-ai task-pointer">
        <div class="task-span1"></div>
     
        <div class="task-flex">
          <template v-if="auth.REPORT_EXPORT">
            <div @click="taskExport(false)">
              <i class="iconfont icon-upload1"></i>
              {{ $t('common.base.export') }}
            </div>
            <div class="task-ml12" @click="taskExport(true)">
              <i class="iconfont icon-upload1"></i>
              {{ $t('common.base.exportAll') }}
            </div>
          </template>
          <div class="task-ml12" @click="tableNames = []">
            {{ $t('common.base.collapse') }}
            <i class="iconfont icon-triangle-down"></i>
          </div>
        </div>
      </div> 

      <!-- S table -->
      <!-- 工单 -->
      <el-table
        v-if="reportType === 'task' || chartSatet === 1 "
        stripe
        border
        :data="tableNames"
        ref="multipleTable"
        header-row-class-name="common-list-table-header taks-list-table-header"
      >
        <el-table-column
          v-for="(item, index) in customizes"
          :key="index"
          :label="item.displayName"
        >
          <template slot-scope="scope">
            
            <template v-if="item.fieldName === 'taskNo'">
              <!-- 工单编号 -->
              <template>
                <a
                  href=""
                  class="view-detail-btn task-list-numbering"
                  @click.stop.prevent="openTaskTab(scope.row.id, scope.row[item.fieldName])"
                >
                  {{scope.row[item.fieldName]}}
                </a>
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'executorUserName'">
              <!-- 负责人 -->
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.executorUserStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.executorUserName}}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'createUserName'">
              <!-- 创建人 -->
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.createUserStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.createUserName}}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'horizontal'">
              <template v-if="isOpenData && scope.row.horizontalStaffId">
                <open-data type='userName' :openid="scope.row.horizontalStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.horizontal}}
              </template>
            </template>
            
            <template v-else>
              {{scope.row[item.fieldName]}}
            </template>
            
          </template>
          
        </el-table-column>
      
      </el-table>
      <!-- 客户 -->
      <el-table
        v-else-if="reportType === 'client' || chartSatet === 4"
        stripe
        border
        :data="tableNames"
        ref="multipleTable"
        header-row-class-name="common-list-table-header taks-list-table-header"
      >
        <el-table-column
          v-for="(item, index) in customercustomizes"
          :key="index"
          :label="item.displayName"
        >
          <template slot-scope="scope">
            
            <template v-if="item.fieldName === 'customerName'">
              <!-- 客户名称 -->
              <template>
                <a
                  href=""
                  class="view-detail-btn task-list-numbering"
                  @click.stop.prevent="openClientTab(scope.row)">
                  {{scope.row[item.fieldName]}}
                </a>
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'executorUserStaffId'">
              <!-- 负责人 -->
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.executorUserStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.executorUserName}}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'horizontal'">
              <template v-if="isOpenData && scope.row.horizontalStaffId">
                <open-data type='userName' :openid="scope.row.horizontalStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.horizontal}}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'customerManagerName'">
              <!-- 客户负责人 -->
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.customerManagerStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.customerManagerName}}
              </template>
            </template>
            
            <template v-else>
              {{scope.row[item.fieldName]}}
            </template>
            
          </template>
          
        </el-table-column>
      </el-table>

      <!-- 之前版本保持不动 后续新曾使用聚合 -->

      <el-table
        v-else
        stripe
        border
        :data="tableNames"
        ref="multipleTable"
        header-row-class-name="common-list-table-header taks-list-table-header">
        <el-table-column
          v-for="(item, index) in aggregateColumn"
          :key="index"  
          :label="item.displayName"
        >         
          <template slot-scope="scope">
            <custom-app-table-column v-if="reportType === 'custom' || chartSatet == 5" :scope="scope" :item="item"></custom-app-table-column>
            <product-table-column v-if="reportType === 'product' || chartSatet === 3" :scope="scope" :item="item"></product-table-column>
          </template>
        </el-table-column>
      </el-table>
      <!-- E table -->
      <!-- 分页 -->
      <div class="spare-parts-foot task-flex task-ai report-spare-parts-foot">
        <span class="task-c90">{{$t('report.system.total',{num:pagination.total})}}</span>
        <el-pagination
          class="comment-list-table-footer-pagination task-span1"
          background
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="pageSize"
          :total="pagination.total"
          :current-page="pageNum"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          layout="prev, pager, next, sizes, jumper"
        >
        </el-pagination>
      </div>  
    </div>
    </div>
  </div>
</template>
<script>
import { t } from '@src/locales';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import echarts from 'packages/Echarts';
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import _ from "lodash";
import {CUSTOMIZE, CUSTOMERCUSTOMIZE, CUSTOM_FORM_PORDUCT, CUSTOM_FORM_PAAS} from '../../common/tableModel'
import {COLORS} from '../../common/colorLModel'

import { formatDate } from 'pub-bbx-utils';

import * as ReportApi from '@src/api/ReportApi.ts';

import { isEmpty } from '@src/util/type'
import qs from '@src/util/querystring2';

import { checkButtonDisplayed } from '@src/util/dom';
import { safeNewDate } from '@src/util/time';

import CustomAppTableColumn from './CustomAppTableColumn.vue'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

import ProductTableColumn from './ProductTableColumn.vue'
import { defaultTableData } from '@src/util/table'
const aggregationFetchFuns = {
  '3': 'aggregationProductData',
  '4': 'aggregationData',
  '5': 'aggregationCustomData'
}
let myChart = null
export default {
  name: 'chart',
  props: {
    type: {
      type: String // 图表类型
    },
    chartList: {
      type: Array
    }, // 数据
    parasm: {
      type: Object
    }, // 参数
    chartSatet:{
      type: Number | String
    }, // 生成的报表判断
    sorts: {
      type: Array | String
    }, // 默认排序
    reportResourceType: {
      type: String,
      default:  ''
    },
    auth: {
      type: Object,
      default: ()=> ({})
    },
    loading: {
      type: Boolean,
    }
  },
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      chartType: '', // 图表icon
      reportType: '', // 报表类型
      sort: t('report.productChart.defaultSort'),
      pageSize: 10,
      pageNum: 1,
      tableNames: [],
      pagination: {},
      productType: '',
      exportPage: 0,
      dataIndex: 0,
      exportParams: {},
      tableTitle: '',
      customizes:CUSTOMIZE,
      customercustomizes: CUSTOMERCUSTOMIZE,
      aggregateColumn: []
    }
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.EXPORT_IN || 0 
    },
    // 是否是工单自定义报表
    isTaskReport(){
      return this.reportType === 'task' || this.chartSatet === 1;
    },    
  },
  watch: {
    type(v) {
      this.tableNames = []
      this.pageSize = 10
      this.pageNum = 1
      if (v === t('common.base.histogram')) {
        this.chartType = 'icon-signal-fill'
        if (this.chartList.length) this.histogram(this.chartList)
      } else if (v === t('common.base.pieChart')) {
        this.chartType = 'icon-piechart-circle-fil'
        if (this.chartList.length) this.pieChart(this.chartList)
      } else if (v == t('common.base.lineChart')) {
        this.chartType = 'icon-fund-fill'
        if (this.chartList.length) this.lineChart(this.chartList)  
      } else {
        this.chartType = 'icon-detail-fill'
        if (this.chartList.length) {
          myChart = echarts.init(document.getElementById('chart'))
          myChart.clear()
        }
        this.getChartTableHeight()
      }
    },
    chartList(v) {
      this.tableNames = []
      this.pageSize = 10
      this.pageNum = 1
      this.initialization()
      this.getChartTableHeight()
    },
    reportResourceType(newVal) {
      this.reportType = newVal
    }
  },
  mounted() {
    const urlSplitArr = window.location.href.split('?')
    let urlParams = {}
    if(urlSplitArr.length > 1) {
      urlSplitArr[1].split('&').forEach(item => {
        urlParams[item.split('=')[0]] = item.split('=')[1]
      })
    }


    this.reportType = urlParams.type || this.reportResourceType
    this.initialization()

    if (this.type === t('common.base.histogram')) {
      this.chartType = 'icon-signal-fill'
    } else if (this.type === t('common.base.pieChart')) {
      this.chartType = 'icon-piechart-circle-fil'
    } else if (this.type == t('common.base.lineChart')) {
      this.chartType = 'icon-fund-fill'
    } else {
      this.chartType = 'icon-detail-fill'
    }

    if (this.sorts) {
      if (this.sorts.direction) {
        this.sort = t('report.productChart.priceSort2')
      } else {
        this.sort = t('report.productChart.priceSort1')
      }
    }
    window.addEventListener('resize', _.debounce(function(){
      myChart.resize();
    }))
  },
  methods: {
    getChartTableHeight() {
      this.$nextTick(()=> {
        try {
          if(this.type === t('common.base.table2') && this.chartList.length) {
            let nav_height = document.getElementById("table-wrap").offsetHeight
            if(nav_height > 500) {
              document.getElementById("chart-table-position").style.height = 500 + "px";
            }else {
              document.getElementById("chart-table-position").style.height = nav_height + "px";
            }
          }
          } catch (error) {
            console.warn(error)
          }
      })
    },
    stateText(item) {
      if (isEmpty(item)) return
      
      this.tableTitle = item[0].value
      this.customercustomizes = CUSTOMERCUSTOMIZE.map((v, index) => {
        if(!index) v.displayName = item[0].value 
        return v
      })
      this.customizes = CUSTOMIZE.map((v, index) => {
        if(!index) v.displayName = item[0].value 
        return v
      })
      if(this.reportType !== 'produce') {
        // 聚合处理 
        switch(this.reportType) {
        case 'custom':
          this.aggregateColumn = this.getTableColumn(item, CUSTOM_FORM_PAAS)
          // console.log(this.getTableColumn(item, CUSTOM_FORM_PAAS))
          break
        case 'product':
          this.aggregateColumn = this.getTableColumn(item, CUSTOM_FORM_PORDUCT)
          break
        default:
        }
      } else {
        if(this.chartSatet === 5 ) this.aggregateColumn = this.getTableColumn(item, CUSTOM_FORM_PAAS)
        if(this.chartSatet === 3 ) this.aggregateColumn = this.getTableColumn(item, CUSTOM_FORM_PORDUCT)
      }

    },

    getTableColumn(item, data) {
      // console.log(item, data);
      return data.map((v, index) => {
        if(!index) v.displayName = item[0].value 
        return v
      })
    },
    // 初始化
    initialization() {
      if (!this.chartList.length) return
      if (this.type === t('common.base.histogram')) {
        this.histogram(this.chartList)
      } else if (this.type === t('common.base.pieChart')) {
        this.pieChart(this.chartList)
      } else if (this.type == t('common.base.lineChart')) {
        this.lineChart(this.chartList)
      }
    },
    // 排序
    handleClick(v) {
      this.sort = v
      let sorts
      switch (v) {
      case t('report.productChart.priceSort1'):
        sorts = [{'property':'total', 'direction':'DESC'}]
        break;
      case t('report.productChart.priceSort2'):
        sorts = [{'property':'total', 'direction':'ASC'}]
        break;      
      default:
        sorts = ''
        break;
      }
      this.tableNames = []
      this.$emit('taskTable', {
        sorts,
      })
    },
    // 转成图片并下载
    convertCanvasToImage() {
      const canvas = document.querySelector('#chart div canvas')
      const img = canvas.toDataURL('image/png');
      const oA = document.createElement('a');
      // TODO国际化待办，是否需要翻译
      oA.download = `${this.type}统计图表`;// 设置下载的文件名，默认是'下载'
      oA.href = img;
      document.body.appendChild(oA);
      oA.click();
      oA.remove();
    },
    rowClassName({row, rowIndex}) {
      this.$set(row, 'dataIndex', rowIndex)
    },
    // 表格
    tabletd(e) {
      this.tableNames = []
      this.pageSize = 10
      this.pageNum = 1
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregationPage(e)
      } else if (this.reportType === 'product' || this.chartSatet === 3) {
        this.aggregationData(e)
      } else {
        this.aggregationData(e)
      }    
    },
    // 柱状图
    histogram(data) {
      this.$nextTick(() => {
        myChart = echarts.init(document.getElementById('chart'))
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} '
          },
          xAxis: {
            type: 'category',
            axisLabel:{
              interval: 0
            },
            data: data.map(item => {return item.name})
          },
          yAxis: {
            type: 'value',
          },
          dataZoom: [
            {
              type: 'slider',
              show: true,
              start: 0,
              end: data.length < 10 ? 100 : 3,
              textStyle: {
                width: 50,
                height: 5,
                overflow: 'truncate'
              }
            }
          ],
          series: [{
            data: data.map(item => {return item.count}),
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(220, 220, 220, 0.8)'
            },
            barCateGoryGap:20,
            barWidth : 30,
            itemStyle: {
              normal: {
                color: '#55b7b4'
              }
            },
            label: {
              show: true,
              position: 'top',
            }
          }],
          backgroundColor: '#fff'
        };
        myChart.setOption(option, true);
        myChart.off('click')
        myChart.on('click', e => {
          this.tabletd(e)
        })
      })
    },
    // 饼图
    pieChart(data) {
      this.$nextTick(() => {
        myChart = echarts.init(document.getElementById('chart'))
        const option = {
          color: COLORS,
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: data.map(item => {return item.name})
          },
          series: [
            {
              name: t('report.customReportAggregate.resource'),
              type: 'pie',
              radius: '55%',
              center: ['50%', '60%'],
              data: data.map(item => {item.value = item.count; return item}),
              label: {
                normal: {
                  show: true,
                  formatter: '{b} : {c} ({d}%)'
                }
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ],
          backgroundColor: '#fff'
        };
        myChart.setOption(option, true);
        myChart.off('click')
        myChart.on('click', e => {
          this.tabletd({name: e.name, data: e.data.value, dataIndex: e.dataIndex})
        })
      })
    },
    // 折线图
    lineChart(data) {
      this.$nextTick(() => {
        myChart = echarts.init(document.getElementById('chart'))
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} '
          },
          xAxis: {
            type: 'category',
            data: data.map(item => {return item.name}),
          },
          yAxis: {
            type: 'value',
          },
          dataZoom: [
            {
              show: true,
              start: 0,
              end: data.length < 10 ? 100 : 3,
              textStyle: {
                width: 50,
                height: 5,
                overflow: 'truncate'
              }
            }
          ],
          series: [{
            data: data.map(item => {return item.count}),
            type: 'line',
            barWidth : 30,
            itemStyle: {
              normal: {
                color: '#55b7b4'
              }
            },
            label: {
              show: true,
              position: 'top',
            }
          }],
          backgroundColor: '#fff'
        };
        myChart.setOption(option, true);
        myChart.off('click')
        myChart.on('click', e => {
          this.tabletd(e)
        })
      })
    },
    // 工单：根据关键字查询工单信息-分页
    async aggregationPage(e) {
      this.$loading.service()
      let item = this.chartList.filter((item, index) => {
        // 单纯按名称来筛选会筛选出错误的数据，所以额外加了按index条件
        return e.name === item.name && e.dataIndex === index
      })[0]
      const {pageSize, pageNum} = this
      this.productType = item.name
      this.exportPage = e.data || e.count
      this.dataIndex = e.dataIndex

      const params = {...this.parasm, aggregationValue: item.id, pageSize, page: pageNum, pageNum}
      this.exportParams = params
      const {result, success} = await ReportApi.aggregationPage(params)

      this.$loading.service().close()
      if (!success) return
      const {list, total} = result
      this.tableNames = list.map(v => {
        v.horizontal = item.name
        v.horizontalStaffId = item.staffId
        v.createDateTime = formatDate(safeNewDate(v.createDateTime).getTime(), 'YYYY-MM-DD HH:mm:ss')
        return v
      })
      this.pagination = {
        total,
      };
    },
    // 客户：根据关键字查询工单信息-分页
    async aggregationData(e) {
      let fetchFun = 'aggregationData'
      let item = this.chartList.filter(item => {return e.name === item.name})[0]
      const {pageSize, pageNum} = this
      this.productType = item.name
      this.exportPage = e.data || e.count

      this.$loading.service()

      const params = {...this.parasm, aggregationValue: item.id, pageSize, page: pageNum, pageNum}
      this.exportParams = params
      if(this.reportResourceType !== 'produce') {
        switch(this.reportResourceType) {
        case 'product':
          fetchFun = 'aggregationProductData'
          break
        case 'custom':
          fetchFun = 'aggregationCustomData'
          params.aggregationValueName = item.id
          params.pageNum = pageNum
          break
        default:
          break
        }
      } else {
        fetchFun = aggregationFetchFuns[this.chartSatet.toString()]
        if(this.chartSatet.toString() === '5') {
          params.aggregationValueName = item.id
          params.pageNum = pageNum
        }
      }
      
    
      const {result, data, success} = await ReportApi[fetchFun](params)

      this.$loading.service().close()
      if (!success) return
      const {list, total} = result ?? data ?? []
      this.tableNames = list.map(v => {
        v.horizontal = item.name
        v.horizontalStaffId = item.staffId
        v.createDateTime = formatDate(safeNewDate(v.createDateTime).getTime(), 'YYYY-MM-DD HH:mm:ss')
        return v
      })
      this.pagination = {
        total,
      };   
    },
    clons() {
      this.tableNames = []
    },
    /**
     * @description 打开工单详情tab
     * @param {String} taskId 工单id
     */
    openTaskTab(taskId, taskNo) {
      if (!taskId) return;

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `task_view_${taskId}`,
      //   title: `工单${taskNo}`,
      //   close: true,
      //   url: `/task/view/${taskId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: 'noHistory=1',
        fromId
      })
    },
    /**
     *
     * @description 打开客户详情
     * @param {object} clientInfo 客户详情
     */
    openClientTab({id}) {
  
      if (!id) return;

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `customer_view_${id}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${id}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
        fromId
      })
    },
    // 导出
    async taskExport(type) {
      this.$loading.service()

      delete this.exportParams.page

      let pageSize
      if (type) {
        pageSize = this.chartList.reduce((c, s) => {return c += s.count}, 0)
      } else {
        pageSize = this.exportPage
      }
      try {

        let params = {...this.exportParams, ...{pageNum: 1, pageSize, aggregationFieldName: this.tableNames.map(item => {return item.horizontal})[0]}}
        if (type) delete params.aggregationValue
          
        if (this.reportType === 'task' || this.chartSatet === 1) {
          await this.$http.post('/excels/custom/taskExport', params)
        } else if (this.reportType === 'product' || this.chartSatet === 3) {
          await this.$http.post('/excels/product/customerExport', params)
        } else if (this.reportType === 'custom' || this.chartSatet === 5) {
          await this.$http.post('/excels/paas/customerExport', params)
        } else {
          await this.$http.post('/excels/custom/customerExport', params)
        }
        window.parent.showExportList();
        window.parent.exportPopoverToggle(true);

        this.$loading.service().close()
      } catch (e) {
        console.error('[export faile]:', e)
        this.$loading.service().close()
      }
    },
    /* 分页条数切换 */
    handleSizeChange(value) {
      this.pageNum = 1
      this.pageSize = value;
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregationPage({name: this.productType, data: this.exportPage, dataIndex: this.dataIndex})
      }
      else {
        this.aggregationData({name: this.productType, data: this.exportPage})
      }
    },
    /* 分页页数切换 */
    handlePageChange(value) {
      this.pageNum = value;
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregationPage({name: this.productType, data: this.exportPage, dataIndex: this.dataIndex})
      }
      else {
        this.aggregationData({name: this.productType, data: this.exportPage})
      }
    },
    // 样式
    styles(icon) {
      let sty;
      if (icon === 'icon-ditu2') {
        sty = 'task-bj9f'
      } else if (icon === 'icon-piechart-circle-fil') {
        sty = 'task-bjf7'
      } else if (icon === 'icon-fund-fill') {
        sty = 'task-bjd1'
      } else if (icon === 'icon-detail-fill' || icon === 'icon-calendar-fill') {
        sty = 'task-bjc4'
      } else {
        sty = 'task-bjc2'
      }
      return sty
    },
    // 导出
    async exportBtn(){
      try{
        if(this.chartList.length > 10000) return this.$platform.alert(this.$t('product.qrcode.tips.tip12',{count:10000}));
        this.$loading.service();

        // 工单和客户使用不同接口导出
        // const api = this.isTaskReport ? 'taskReportExport' : 'customReportExport';
        // console.log(this.$parent)
        
        const params = {...this.parasm, aggregationFieldName: this.$parent.statisticTypeList.find(item => item.label === this.parasm.aggregationStr).value ?? ''}
        const types = {
          '1': 'task',
          '2': 'event',
          '3': 'product',
          '4': 'client',
          '5': 'custom',
        }
        let reportType = this.reportType !== 'produce' ? this.reportType : types[this.chartSatet.toString()]
        const { status, result: resultMessage, message } = await ReportApi.aggregateReportExport(params, reportType);

        if(status === 0){
          this.$message.success(resultMessage ?? message);
          window.parent.showExportList()
          window.parent.exportPopoverToggle(true)
        }else {
          this.$platform.alert(message);
        }
        this.$loading.service().close();
      }catch(e){
        console.log('exportBtn', e);
        this.$loading.service().close();
      }
    },
  },
  components: {
    [NoDataViewNew.name]: NoDataViewNew,
    CustomAppTableColumn,
    ProductTableColumn
  }
}
</script>
<style lang="scss" scoped>
.chart-header {
    color: rgba(0, 0, 0, 0.65);
    height: 56px;
    background-color:#FAFAFA;
    padding: 0 12px;
    font-size: 14px;
    border-radius: 4px 4px 0 0;
    border-right: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
    .iconfont {
        font-size: 14px;
    }
    .chart-icon {
      width: 32px;
      height: 32px;
      border-radius: 4px;
      text-align: center;
      line-height: 32px;
      color: #fff;
    }
}
.chart-content {
    background-color: #fff;
    width: 100%;
    height: 400px!important;
    padding: 12px;
    border-right: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
    #chart {
        width: 100%;
        height: 100%;
    }
}
.guide-point{
  background-color: white
}
.chart > .guide-point {
  margin-top: 30px;
}
.chart-table {
  width: 100%; 
  max-height: 500px;
  overflow: hidden;
  overflow-y: scroll;
}
#chart-table-position {
  position: relative; 
  width: 100%; 
  max-height: 500px;
  .el-table {
    position: absolute;
  }
}
.table {
  width: 100%;
  position: relative; 
}
.export-table-style {
  width: 100%; 
  position: absolute;
}
.spare-parts-foot {
    margin: 12px 0 12px 0;
}
.task-export-text {
  margin-right: 20px;
}
</style>